package com.haidechizi.i18n.common.interceptor;

import com.haidechizi.i18n.common.config.Configuration;
import com.haidechizi.i18n.common.constant.ParamConstant;
import com.haidechizi.i18n.common.utils.GlobalUtils;
import com.haidechizi.i18n.common.utils.RequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * web层，获取设置的语言
 * <p>
 * 从header中获取当前设置的语言，放到GlobalUtils中
 *
 * @see GlobalUtils
 */
public class I18nLanguageInterceptor implements HandlerInterceptor {

    @Autowired
    private Configuration configuration;

    /**
     * 获取header中的语言
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String language = RequestUtils.getLocale(request, configuration.getI18nLocale());
        if (StringUtils.isBlank(language)) {
            language = configuration.getDefaultLanguage();
        }
        String translate = request.getHeader(ParamConstant.TRANSLATE);
        GlobalUtils.setLanguage(language);
        GlobalUtils.setTranslate(translate);
        return true;
    }

    /**
     * 移除设置的语言
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        GlobalUtils.removeLanguage();
        GlobalUtils.removeTranslate();
    }
}
